package com.qiji.video.util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

import java.io.IOException;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 *         电影
 *         https://api.web.360kan.com/v1/block?blockid=99&callback=__jp33
 *
 *         https://api.web.360kan.com/v1/block?blockid=528&size=12&callback=__jp8  限免大片
 *         https://api.web.360kan.com/v1/rank?cat=2&size=8&callback=__jp10  排行榜
 *         https://api.web.360kan.com/v1/block?blockid=90&size=14&callback=__jp17  网络热播
 *         https://api.web.360kan.com/v1/block?blockid=500&size=7&callback=__jp18 高分系列·重温经典
 *         https://api.web.360kan.com/v1/block?blockid=187&size=14&callback=__jp20 此生不悔入华夏！来世还做中国人
 *         https://api.web.360kan.com/v1/block?blockid=92&size=11&callback=__jp9 电影热播榜
 *         https://api.web.360kan.com/v1/block?blockid=567&size=7&callback=__jp59
 *         https://api.web.360kan.com/v1/block?blockid=499&size=7&callback=__jp62
 *         https://api.web.360kan.com/v1/block?blockid=97&callback=__jp3
 *         https://api.web.360kan.com/v1/block?blockid=529&size=7&callback=__jp26
 *
 *         电视剧
 *         https://api.web.360kan.com/v1/block?blockid=503&callback=__jp115
 *
 *         https://api.web.360kan.com/v1/block?blockid=131&size=14&callback=__jp120
 *         https://api.web.360kan.com/v1/rank?cat=3&size=8&callback=__jp121
 *         https://api.web.360kan.com/v1/block?blockid=42&size=12&callback=__jp189
 *         https://api.web.360kan.com/v1/rank?cat=4&size=8&callback=__jp190
 *         https://api.web.360kan.com/v1/block?blockid=41&size=11&callback=__jp191
 *         https://api.web.360kan.com/v1/block?blockid=35&size=11&callback=__jp193
 *         https://api.web.360kan.com/v1/block?blockid=180&size=11&callback=__jp19
 *         https://api.web.360kan.com/v1/block?blockid=515&size=20&callback=__jp8
 *
 *         综艺
 *         https://api.web.360kan.com/v1/block?blockid=227&callback=__jp15
 *
 *         https://api.web.360kan.com/v1/block?blockid=214&size=20&callback=__jp19
 *         https://api.web.360kan.com/v1/block?blockid=43&size=11&callback=__jp20
 *         https://api.web.360kan.com/v1/block?blockid=42&size=12&callback=__jp22
 *         https://api.web.360kan.com/v1/block?blockid=41&size=11&callback=__jp24
 *         https://api.web.360kan.com/v1/block?blockid=40&size=11&callback=__jp25
 *         https://api.web.360kan.com/v1/block?blockid=35&size=11&callback=__jp26
 *
 *         儿童
 *         https://api.web.360kan.com/v1/block?blockid=3&callback=__jp47
 *
 *         https://api.web.360kan.com/v1/block?blockid=28&callback=__jp138
 *         https://api.web.360kan.com/v1/block?blockid=26&size=24&callback=__jp140
 *         https://api.web.360kan.com/v1/rank?cat=6&size=8&callback=__jp141
 *         https://api.web.360kan.com/v1/block?blockid=25&size=14&callback=__jp165
 *         https://api.web.360kan.com/v1/block?blockid=6&size=7&callback=__jp167
 *         https://api.web.360kan.com/v1/block?blockid=15&size=7&callback=__jp168
 *         https://api.web.360kan.com/v1/block?blockid=9&size=7&callback=__jp169
 *         https://api.web.360kan.com/v1/block?blockid=459&size=7&callback=__jp170
 *
 *         动漫
 *         https://api.web.360kan.com/v1/block?blockid=79&callback=__jp54
 *
 *         https://api.web.360kan.com/v1/block?blockid=73&size=12&callback=__jp147
 *         https://api.web.360kan.com/v1/block?blockid=72&size=14&callback=__jp148
 *         https://api.web.360kan.com/v1/rank?cat=5&size=8&callback=__jp149
 *         https://api.web.360kan.com/v1/block?blockid=61&size=7&callback=__jp153
 *         https://api.web.360kan.com/v1/block?blockid=523&size=7&callback=__jp154
 *         https://api.web.360kan.com/v1/block?blockid=63&size=7&callback=__jp9
 *         https://api.web.360kan.com/v1/block?blockid=62&size=7&callback=__jp10
 *         https://api.web.360kan.com/v1/block?blockid=416&size=7&callback=__jp11
 *
 *
 */
public class VideoData {
    // api
    private static final String JDBC_URL="jdbc:mysql://47.106.190.23:3306/video_website?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC";
    private static final String USERNAME="root";
    private static final String PASSWORD="Qjsys1218.";

    private WebClient webClient;
    private Connection connection;
    private PreparedStatement statement;
    // 执行初始化
    public VideoData(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            connection = DriverManager.getConnection(JDBC_URL,USERNAME,PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        webClient=new WebClient(BrowserVersion.CHROME);
        webClient.getOptions().setActiveXNative(false); // 不启用ActiveX
        webClient.getOptions().setCssEnabled(false);// 是否启用CSS，因为不需要展现页面，所以不需要启用
        webClient.getOptions().setUseInsecureSSL(true); // 设置为true，客户机将接受与任何主机的连接，而不管它们是否有有效证书
        webClient.getOptions().setJavaScriptEnabled(true); // 很重要，启用JS
        webClient.getOptions().setDownloadImages(false);// 不下载图片
        webClient.getOptions().setThrowExceptionOnScriptError(false);// 当JS执行出错的时候是否抛出异常，这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);// 当HTTP的状态非200时是否抛出异常，这里选择不需要
        webClient.getOptions().setTimeout(15 * 1000); // 等待15s
        webClient.getOptions().setConnectionTimeToLive(15 * 1000);
        webClient.waitForBackgroundJavaScript(30000);// 异步JS执行需要耗时，所以这里线程要阻塞30秒，等待异步JS执行结束
        webClient.addRequestHeader("user-agent",
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36");
        webClient.addRequestHeader("Content-Type","application/json");
    }

    public void insertData(){
        HtmlPage page=null;
        try {
            // 通过webClient请求
            page=webClient.getPage("https://api.web.360kan.com/v1/block?blockid=416&size=7&callback=__jp11");
            // 获取页面
            String data = page.getBody().asText();
            // 去除多余字符串
            data=data.substring(data.indexOf("(")+1,data.length()-2);
            // json
            JSONObject jsonObject=new JSONObject(data);
            JSONObject jsonObject1=new JSONObject(jsonObject.getJSONObject("data").toString());
            // 获取lists数组
            JSONArray lists = jsonObject1.getJSONArray("lists");
            // 循环执行插入
            for (int i = 0; i < lists.length(); i++) {
                // 获取ent_id（对应电影的id）
                JSONObject jsonObject2 = new JSONObject(lists.get(i).toString());
                // 插入mysql
                insert(jsonObject2.get("ent_id").toString());
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }
    }

    private void insert(String ent_id){
        HtmlPage page=null;
        try {
            // 通过ent_id获取详细信息
            page=webClient.getPage("https://api.web.360kan.com/v1/detail?cat=4&id="+ent_id+"&callback=__jp0");
            String data = page.getBody().asText();
            data = data.substring(6,data.length()-2);
            // json
            JSONObject jsonObject=new JSONObject(data);
            JSONObject jsonObject1=new JSONObject(jsonObject.getJSONObject("data").toString());
			/*
				name 1
				file_name
				back_img 1
				cover_img 1
				director 1
				starring 1
				region 1
				public_name 1
				description 1
				synopsis 1
				sort_num
			 */
//            System.out.println(
//                    new VideoDataEntity(
//                            jsonObject1.get("title").toString(),
//                            jsonObject1.get("cdncover").toString(),
//                            jsonObject1.get("cdncover").toString(),
////                            jsonObject1.get("moviecategory").toString(),
//                            jsonObject1.getJSONArray("director").toString(),
//                            jsonObject1.getJSONArray("actor").toString(),
//                            jsonObject1.getJSONArray("area").toString(),
//                            new Timestamp(
//                                    new SimpleDateFormat("yyyy-MM-dd").parse(jsonObject1.get("pubdate").toString()).getTime()
//                            ),
//                            jsonObject1.get("description").toString(),
//                            jsonObject1.get("description").toString(),
//                            Integer.parseInt(jsonObject1.get("rank").toString())
//                    )
//            );
            // jdbc
            String sql="insert into " +
                    "videos(name,back_img,cover_img,director,starring,region,public_time,description,synopsis,sort_num) " +
                    "values (?,?,?,?,?,?,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1,jsonObject1.get("title").toString());
//            statement.setString(2,jsonObject1.getJSONArray("pic_lists").get(0));
            statement.setString(2,jsonObject1.get("cdncover").toString());
            statement.setString(3,jsonObject1.get("cdncover").toString());
            statement.setString(4,jsonObject1.getJSONArray("director").get(0).toString());
            statement.setString(5, jsonObject1.getJSONArray("actor").get(0).toString());
            statement.setString(6, jsonObject1.getJSONArray("area").get(0).toString());
            statement.setTimestamp(7,new Timestamp(
                    new SimpleDateFormat("yyyy-MM-dd").parse(jsonObject1.get("pubdate").toString()).getTime()
            ));
            statement.setString(8,jsonObject1.get("description").toString());
            statement.setString(9,jsonObject1.get("description").toString());
            statement.setInt(10,Integer.parseInt(jsonObject1.get("rank").toString()));
            statement.execute();
        } catch (IOException | JSONException | ParseException | SQLException e) {
            e.printStackTrace();
        }
    }
}
